import React, { useEffect, useState } from 'react'
import { queryComment, deleteComment, getBlogDetail } from '@/api'
import style from './index.module.scss'
import { showTime, cp } from '@/utils/utils'
import { FullscreenOutlined, DeleteFilled } from '@ant-design/icons'
import { Tooltip, Popconfirm, message, Table } from 'antd'
import { useHistory } from 'react-router-dom'
import CommentModal from '../commentModal'
import event from '@/utils/event'
export default ({
  blogId,
  blogTitle,
}: {
  blogId?: number
  blogTitle?: string
}) => {
  const history = useHistory()
  const [list, setList] = useState<BlogCommentList[]>([])
  const [onReplayStatus, setOnReplayStatus] = useState(false)
  const [commentModalStatus, setCommentModalStatus] = useState<{
    show: boolean
    comment: BlogCommentList | null
    commentIndex: number
  }>({
    show: false,
    comment: null,
    commentIndex: -1,
  })
  const getAllList = async () => {
    const { data } = await queryComment({
      pageNum: 0,
      size: 10,
    })
    setList(data)
  }
  const getBlogCommentList = async () => {
    const { data } = await getBlogDetail({ blogId: blogId as number })
    const dataList = cp(data.commentList)
    dataList.forEach((el: BlogCommentList) => {
      el.blogTitle = blogTitle as string
    })
    setList(dataList)
  }

  const deleteCommentFn = async (comment: BlogCommentList, index: number) => {
    const { status, msg } = await deleteComment([comment.commentId])
    if (status) {
      const listCopy = cp(list)
      listCopy.splice(index, 1)
      setList(listCopy)
      message.success('删除成功')
    } else {
      message.warning(msg)
    }
  }
  const deleteCommentRender = () => {
    const listCopy = cp(list)
    listCopy.splice(commentModalStatus.commentIndex, 1)
    setList(listCopy)
    setCommentModalStatus({
      ...commentModalStatus,
      show: false,
    })
  }
  const deleteCommentRelyRender = () => {
    const cpList: BlogCommentList[] = cp(list)
    cpList[commentModalStatus.commentIndex].reply = ''
    setList(cpList)
    setCommentModalStatus({
      ...commentModalStatus,
      comment: cpList[commentModalStatus.commentIndex],
    })
  }
  const offCommentModal = () => {
    setCommentModalStatus({
      ...commentModalStatus,
      show: false,
    })
  }
  const columns = [
    {
      title: '文章标题',
      dataIndex: 'blogTitle',
      render: (text: string, el: BlogCommentList) => {
        return (
          <div
            className={style.title}
            onClick={() => history.push(`/detail/${el.blogId}`)}
          >
            {text}
          </div>
        )
      },
      align: 'center' as 'center',
    },
    {
      title: '评论内容',
      dataIndex: 'content',
      width: '50%',
      render: (text: string) => <div className={style.content}>{text}</div>,
      align: 'center' as 'center',
    },
    {
      title: '评论时间',
      dataIndex: 'creationTime',
      render: (text: string) => <div>{showTime(text)}</div>,
      align: 'center' as 'center',
    },
    {
      title: '操作',
      align: 'center' as 'center',
      dataIndex: 'content',
      render: (_: any, el: BlogCommentList, index: number) => {
        return (
          <div>
            <Tooltip title="查看详情">
              <FullscreenOutlined
                className={style.icon}
                onClick={() => {
                  setCommentModalStatus({
                    show: true,
                    comment: el,
                    commentIndex: index,
                  })
                }}
              />
            </Tooltip>
            {
              <Popconfirm
                placement="topRight"
                title={'确定要删除这条评论吗?'}
                onConfirm={() => deleteCommentFn(el, index)}
                okText="删除"
                cancelText="取消"
              >
                <Tooltip title="删除">
                  <DeleteFilled className={style.icon} />
                </Tooltip>
              </Popconfirm>
            }
          </div>
        )
      },
    },
  ]
  useEffect(() => {
    // 如果存在id则查询当前文章的评论,否则查询所有评论
    if (blogId) {
      getBlogCommentList()
    } else {
      getAllList()
    }
  }, [blogId]) //  eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (!list.length) return
    if (commentModalStatus.commentIndex === -1) return
    if (onReplayStatus) return
    setOnReplayStatus(true)
    event.on('submitReply', (reply: string) => {
      event.off('submitReply')
      setOnReplayStatus(false)
      const cpList: BlogCommentList[] = cp(list)
      cpList[commentModalStatus.commentIndex].reply = reply
      setList(cpList)
      setCommentModalStatus({
        ...commentModalStatus,
        comment: cpList[commentModalStatus.commentIndex],
      })
    })
  }, [list, commentModalStatus, onReplayStatus])
  return (
    <div className={style.manage}>
      <div className={style.list_row}>
        <CommentModal
          deleteCommentRelyRender={deleteCommentRelyRender}
          offCommentModal={offCommentModal}
          deleteCommentRender={deleteCommentRender}
          getBlogTitle={() => blogTitle as string}
          {...commentModalStatus}
        />
        <Table
          rowKey="commentId"
          pagination={false}
          columns={blogId ? columns.slice(1, columns.length) : columns}
          dataSource={list}
        />
      </div>
    </div>
  )
}
